const {comMysql} = require("../db/mysql")
const fs = require("fs")

const addMusic = (req,res)=>{
    let {name,singer,music} = req.body
    let sql = `insert into music(name,singer,time,music) values (?,?,?,?)`
    let time = new Date().getTime()+''
    let arr = [name,singer,time,music]
    return comMysql(sql,arr)
}
const deleteMusic = async (req,res)=>{
    let {id} = req.body
    let sql = `delete from music where id = ?`
    let arr = [id]
    let data = await searchMusicfromId(req,res)
    if(data.length>0&&data[0].music){
        let num = data[0].music.indexOf("?")      
        let next1=data[0].music.substring(num)
        let next2=next1.split("&")[0].split("=")[1]
        let next3 = "./"+next2
        if(fs.existsSync(next3)){
          fs.unlink(next3,(err)=>{
            if(!err){
              console.log("删除成功");
            }else{
              console.log("删除失败");
            }
          })
        }
      }
    return comMysql(sql,arr)
}
const Music = (req,res)=>{
  let {music} = req.query
  music = "http://localhost:3001/api/upload/music?music="+music
  let sql = "select * from music where music = ?"
  let arr = [music]
  return comMysql(sql,arr)
}
const searchMusicfromId = (req,res)=>{
    let {id} = req.query
    let sql = `select * from music where id = ?`
    let arr = [id]
    return comMysql(sql,arr)
}

const searchMusic = (req,res)=>{
    let sql = `select * from music`
    return comMysql(sql)
}
module.exports = {
    addMusic,
    deleteMusic,
    searchMusic,
    Music,
    searchMusicfromId,
}